<template>
	<view class="content" @tap="onTap" ref="chatSessionRef">
		<topBarNvue></topBarNvue>
		<!--列表区域-->
		<view class="content-contacts">
			<view v-for="(chatSession, index) in chatSessionList" @touchend="changeGrayIndex = -1"
			 @touchstart="handleTouchStart(index)" 
			 @tap="handleClick(chatSession)" 
			 @longpress="onLongPress(index)"
			:class="{active: chatSession.topType != 0}"
			:style="{backgroundColor: changeGrayIndex == index? '#f0f0f0' : ''}"
			class="contact-item">
				<view class="contact-item-content">
					<view>
						<image
							v-if="chatSession.contactId != 'Urobot' && chatSession.avatar"
							:src="chatSession.avatar"
							mode="scaleToFill"
							class="contact-avatar"
						/>
						<image
							v-else-if="chatSession.contactId = 'Urobot'"
							:src="Robot"
							mode="scaleToFill"
							class="contact-avatar"
						/>
						<view v-else class="contact-avatar-no">{{ chatSession.contactName[0] }}</view>
					</view>
					<!--文本区域-->
					<view class="contact-text-area">
						<view class="contact-text-top">
							<text class="contact-name">{{chatSession.contactName}}</text>
							<text class="contact-time">{{ formatData(chatSession.lastReceiveTime) }}</text>
						</view>
						<view class="contact-text-bottom">
							<text class="contact-last-message">{{ chatSession.lastMessage }}</text>
							<view :class="noReadCountStyle(chatSession.noReadCoun)" v-show="chatSession.noReadCoun > 0"  class="contact-unread-count">{{ chatSession.noReadCoun > 99 ? '99+' : chatSession.noReadCoun }}</view>
						</view>
					</view>
				</view>
				<view class="contact-item-top" v-if="operationIndex == index">
					<view class="contact-item-tooltip" @tap.stop>
						<view @tap="handleDelete(chatSession)">删除</view>
						<view @tap="handleTop(chatSession)">
							<text v-if="chatSession.topType != 0">取消置顶</text>
							<text v-else>置顶</text>
						</view>
						<view @tap="handleUnread(chatSession)">标为未读</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted} from 'vue';
import topBarNvue from '../../components/top_bar.nvue';
import {onLoad} from '@dcloudio/uni-app';
import {selectUserSessionList} from '../../db/ChatSessionUserModel'
import { update } from '../../db';
import { formatData } from '../../util/time';
import { useSessionListStore } from '../../store/sessionList';
import { setStorageLocalSessionId } from '../../plus/store/UserData';
import { currentSessionStore } from '../../store/session';
import Robot from '../../static/login/robot.jpg'


const sessionListStore = useSessionListStore()
const currentSession = currentSessionStore()
//会话列表
const chatSessionList = ref([])

//查询会话列表
const onLoadSessionData = async () => {
    const dataList = await selectUserSessionList()
	console.log("获取会话列表", dataList)
	//将数据放到store中
	sessionListStore.setSessionList(dataList)
	chatSessionList.value = sessionListStore.getSessionList
	//排序
	sortChatSessionList(chatSessionList.value)
}
//根据未读数量设置样式
const noReadCountStyle = (noReadCount) => {

	if(noReadCount > 1 && noReadCount < 10){
		return "contact-unread-count"
	}else if(noReadCount >= 10){
		return "contact-unread-count-more10"
	}
}
//长按事件，展示操作菜单
const operationIndex =ref(-1)
const chatSessionRef = ref(null)
const onLongPress = (index) => {
	operationIndex.value = index
	//更改contact-item的背景样式
	chatSessionRef.value.style = 'red'
}
//整个页面点击事件，隐藏操作菜单
const onTap = () => {
	operationIndex.value = -1
}
//置顶发送信息
const handleTop = async (chatSession) => {
    chatSession.topType = chatSession.topType === 0 ? 1: 0;
    //排序
    sortChatSessionList(chatSessionList.value);
	//更新数据库
    const paramObject = {
        userId: chatSession.userId,
        contactId: chatSession.contactId
    }
    const sessionInfo = {
        topType: chatSession.topType
    }
    await update("chat_session_user", sessionInfo, paramObject)
}
//点击每个item事件(联系人)
const handleClick = (chatSession) => {
	if(operationIndex.value == -1){
		//本地储存sessionId
		setStorageLocalSessionId(chatSession.sessionId)
		//清除气泡
		chatSession.noReadCoun = 0
		//设置当前session
		console.log("设置当前session", chatSession)
		currentSession.setSession(chatSession)
		//跳转到聊天页面
		uni.navigateTo({
			url: '/pages/index/message?userId=' + 
			chatSession.userId + 
			'&contactId=' + 
			chatSession.contactId + 
			'&contactName=' + 
			chatSession.contactName + 
			'&sessionId=' + 
			chatSession.sessionId +
			'&contactType=' + 
			chatSession.contactType
		})
	}
}

//点击单个item事件，item变灰色
const changeGrayIndex = ref(-1)
const handleTouchStart = (index) => {
	//item变灰色
	changeGrayIndex.value = index
}
//会话排序
const sortChatSessionList = (dataList) => {
    dataList.sort((a, b) => {
        const topTypeResult = b['topType'] - a['topType']
        if(topTypeResult === 0){
            return b['lastReceiveTime'] - a['lastReceiveTime']
        }
        return topTypeResult
    })
}
onLoad((options) => {
	console.log("获取新页面参数", options.messageType)
})
onMounted(() => {
	onLoadSessionData()
})
</script>

<style lang="scss" scoped> 
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
		width: 100%;
		.content-contacts{
			height: 100%;
			width: 100%;
			.active{
				background-color: #ddeffb;
			}
			.contact-item{
				border-bottom: 1px solid #f0f0f0;
				width: 100%;
				padding: 13rpx;
				position: relative;
				.contact-item-content{
					display: flex;
					align-items: center;
				}
				.contact-item-top{
					position: absolute;
					top: -50%;
					//居中
					left: 50%;
					transform: translateX(-50%);
					display: flex;
					.contact-item-tooltip{
						//宽度适应文字宽度
						display: inline-flex;
						font-size: 20rpx;
						background-color: #333333;
						color: #ffffff;
						align-items: center;
						justify-content: center;
						border-radius: 10rpx;
						view{
							padding: 10rpx 20rpx 10rpx 20rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							border-right: #f0f0f07b 1rpx solid;
							&:last-child{
								border-right: none;
							}
						}
					}
				}
				.contact-avatar{
					height: 80rpx;
					width: 80rpx;
					border-radius: 50%;
				}
				.contact-avatar-no{
					height: 80rpx;
					width: 80rpx;
					border-radius: 50%;
					font-size: 30rpx;
                    background-color: #c1c1c1;
                    text-align: center;
                    line-height: 80rpx;
				}
			}
			.contact-text-area{
				display: flex;
				flex-direction: column;
				padding: 0 20rpx 0 20rpx;
				width: 100%;
				.contact-text-top{
					display: flex;
					width: 100%;
					.contact-name{
						font-size: 30rpx;
					}
					.contact-time{
						margin-left: auto;
						color: #8f8f94;
						font-size: 20rpx;
					}
				}
				.contact-text-bottom{
					display: flex;
					align-items: center;
					margin-top: 4rpx;
					.contact-last-message{
						font-size: 25rpx;
						color: #8f8f94;
					}
					.contact-unread-count{
						margin-left: auto;
						font-size: 20rpx;
						height: 29rpx;
						width: 29rpx;
						text-align: center;
						line-height: 29rpx;
						border-radius: 100px;
						background-color: #fa5151;
						color: white;
						font-weight: bolder;
					}
					.contact-unread-count-more10{
						margin-left: auto;
						font-size: 20rpx;
						text-align: center;
						line-height: 29rpx;
						height: 29rpx;
						width: 43rpx;
						border-radius: 15rpx;
						background-color: #fa5151;
						color: white;
						font-weight: bolder;
					}
				}
			}
		}
	}
</style>
